import { prop, Ref, modelOptions, pre } from '@typegoose/typegoose'
import { Types } from 'mongoose'
import bcrypt from 'bcrypt'
import { getProviderByTypegooseClass } from '@app/transformers/model.transformer'
import { OAuth } from '@app/modules/auth/auth.model'

const SALT_ROUNDS = 10;
@pre<User>('save', async function (next) {
  // 仅当密码被修改时才加密（包括新创建）
  if (!this.isModified('password')) return next()

  try {
    if (this.password) {
      // 生成盐并加密
      const salt = await bcrypt.genSalt(SALT_ROUNDS)
      this.password = await bcrypt.hash(this.password, salt)
      next()
    } else {
      next()
    }
  } catch (error) {
    next(error as Error)
  }
})
@modelOptions({
  schemaOptions: {
    timestamps: true,
    _id: true,
  },
})
export class User {
  _id?: Types.ObjectId

  @prop()
  username?: string

  @prop()
  password?: string

  @prop({ unique: true, sparse: true })
  email?: string

  @prop({ unique: true, sparse: true })
  telphone?: number

  @prop({ default: '' })
  nickname?: string

  @prop()
  avatar?: string

  @prop({ ref: () => OAuth, localField: '_id', foreignField: 'user' })
  oauthAccounts?: Ref<OAuth>[]

  // // 比较密码
  // public async comparePassword(password: string): Promise<boolean> {
  //   return bcrypt.compare(password, this.password!)
  // }
}


export const UserProvider = getProviderByTypegooseClass(User)

